<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="closeDialog"
    class=""
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <!-- <div class="title-gra plr30">
      <div class="grab gra-r">
        <span class="grab gra-l"></span>
      </div>
    </div> -->
    <div class="role">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="ruleForm.roleName" :disabled="disabled"></el-input>
        </el-form-item>
        <!--
        <el-form-item label="安全等级：" prop="securityLevelId">
          <el-select v-model="ruleForm.securityLevelId" placeholder="请选择">
            <el-option
              v-for="item in levelOptions"
              :key="item.securityLevelId"
              :label="item.securityLevelName"
              :value="item.securityLevelId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        -->
        <el-form-item label="角色期限：" prop="roleLimit">
          <el-date-picker
            :editable="false"
            style="width:100%"
            :picker-options="pickerOptionRoleLimit"
            v-model="ruleForm.roleLimit"
            type="date"
            placeholder="选择时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="可访问数据期限：" style="padding-left:10px">
          <!--
                    <div style="display:flex;">
                        <el-date-picker style="width:100%"
                            v-model="ruleForm.startTime"
                            type="datetime"
                            placeholder="开始时间">
                        </el-date-picker>
                        -
                        <el-date-picker style="width:100%"
                            v-model="ruleForm.endTime"
                            type="datetime"
                            placeholder="结束时间">
                        </el-date-picker>
                    </div>-->
          <el-date-picker
            :editable="false"
            style="width:100%;margin-left:-10px"
            v-model="ruleForm.datetimerange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="角色描述：" style="padding-left:10px">
          <el-input
            style="margin-left:-10px"
            type="textarea"
            placeholder="请输入内容"
            v-model="ruleForm.roleDescription"
            :autosize="{ minRows: 4, maxRows: 12 }"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="mr-btn">
        <el-button class="def-btn-sty"  @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { addRole, updateRole, securityLevel } from "@/api/roleApi.js";
export default {
  data() {
    var validateRoleName = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入角色名称"));
      } else if (value && !/^[a-zA-Z0-9\u4E00-\u9FA5]{4,20}$/.test(value)) {
        callback(new Error("格式不正确，支持4-20个英文，中文，或数字"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      disabled: false,
      title: "",
      levelOptions: [],
      ruleForm: {
        id: "",
        roleName: "",
        securityLevelId: "",
        roleLimit: "",
        datetimerange: "",
        roleDescription: ""
      },
      loading: false,
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur,change" },
          { validator: validateRoleName, trigger: "blur" }
        ],
        securityLevelId: [
          { required: true, message: "请选择安全等级", trigger: "change" }
        ],
        roleLimit: [
          { required: true, message: "请选择结束时间", trigger: "change" }
        ]
      },
      pickerOptionRoleLimit: {
        disabledDate: time => {
          return time.getTime() < new Date() - 3600 * 1000 * 24;
        }
      }
    };
  },
  methods: {
    openDialogVisible(val, data) {
      // this.initSecurityLevel();
      this.$nextTick(() => {
        this.disabled = val === "edit" ? true : false;
        val == "edit" ? (this.title = "编辑角色") : (this.title = "新增角色");
        this.dialogVisible = true;
        if (val == "edit") {
          this.ruleForm.id = data.id;
          this.ruleForm.roleName = data.roleName;
          //this.ruleForm.securityLevelId = parseInt(data.securityLevelId);
          this.ruleForm.roleLimit = data.roleLimit
            ? this.$options.filters.parseTime(data.roleLimit)
            : "";
          this.ruleForm.roleDescription = data.roleDescription;
          data.roleDataStartTime
            ? (this.ruleForm.datetimerange = [
                this.$options.filters.parseTime(data.roleDataStartTime),
                this.$options.filters.parseTime(data.roleDataEndTime)
              ])
            : (this.ruleForm.datetimerange = ["", ""]);
        }
      });
    },
    // initSecurityLevel() {
    //   this.loading = true;
    //   securityLevel()
    //     .then(res => {
    //       this.levelOptions = res;
    //       this.loading = false;
    //     })
    //     .catch(err => {
    //       this.loading = false;
    //       console.log(err);
    //     });
    // },
    closeDialog() {
      this.$emit("callBack");
      this.$refs["ruleForm"].resetFields();
      this.$refs["ruleForm"].clearValidate();
      this.dialogVisible = false;
    },
    save() {
      this.$refs["ruleForm"].validate(valid => {
        var roleDataStartTime, roleDataEndTime;
        if (this.ruleForm.datetimerange) {
          roleDataStartTime = this.ruleForm.datetimerange[0];
          roleDataEndTime = this.ruleForm.datetimerange[1];
        } else {
          roleDataStartTime = "";
          roleDataEndTime = "";
        }
        if (valid) {
          let params = {
            roleName: this.ruleForm.roleName,
            securityLevelId: this.ruleForm.securityLevelId,
            roleLimit: this.ruleForm.roleLimit,
            roleDataStartTime: roleDataStartTime,
            roleDataEndTime: roleDataEndTime,
            roleDescription: this.ruleForm.roleDescription
          };
          if (this.title == "新增角色") {
            addRole(params).then(res => {
              if (res) {
                this.$message.success("创建成功");
                this.closeDialog();
              } else {
                this.$message.error(res.data.message);
              }
            });
          } else if (this.title == "编辑角色") {
            updateRole(this.ruleForm.id, params).then(res => {
              if (res) {
                this.$message.success("修改角色成功");
                this.closeDialog();
              } else {
                this.$message.error("修改角色失败");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
